package main

import (
	"net/http"
	"qiyang.com/mychain/core"
	"encoding/json"
	"io"
)

//定义全局的区块链属性
var blockchain *core.Blockchain

//启动服务
func run()  {
	//定义两个API，映射到两个处理函数
	http.HandleFunc("/blockchain/get", blockchainGetHandler)
	http.HandleFunc("/blockchain/write", blockchainWriteHandler)
	//监听端口8888
	http.ListenAndServe("localhost:8888", nil)
}

//获取当前区块链信息
func blockchainGetHandler(w http.ResponseWriter, r *http.Request){

	//将区块链数据进行JSON化
	bytes , error := json.Marshal(blockchain)
	//异常捕获
	if error != nil {
		http.Error(w, error.Error(), http.StatusInternalServerError)
		return
	}
	//写到响应中的输出流
	io.WriteString(w, string(bytes))

}

//写入新增区块，并获取最新的区块链信息
func blockchainWriteHandler(w http.ResponseWriter, r *http.Request){
	//获取需要写入的区块数据（获取参数）
	blockData := r.URL.Query().Get("data")
	//将数据写入区块链中
	blockchain.SendData(blockData)
	//返回当前区块链的最新数据
	blockchainGetHandler(w,r)
}

//程序入口
func main()  {
	//初始化创世区块，并添加到区块链中
	blockchain = core.NewBlockchain()
	//启动服务
	run()
}
